package com.itheima.web.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* 登录认证过滤器:
*   对未登录而直接访问pages页面和servlet方法的请求进行拦截
* */
@WebFilter(urlPatterns = {"/pages/*","/store/*","/system/*"})
public class AuthenticationFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //ServletRequest 无法使用getSession方法,需要进行强转
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        //从session中获取user
        Object user = request.getSession().getAttribute("user");
        //如果为null,说明没有登录,重定向到登录页面
        if(user==null){
            //获取拦截到的路径,保存到session中,后期登录成功后跳转到这个路径中
            String requestURI = request.getRequestURI();
            request.getSession().setAttribute("sendRedirect",requestURI);
            //重定向到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }
        chain.doFilter(req, resp);
    }
    public void init(FilterConfig config) throws ServletException {}
    public void destroy() {}

}
